<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import {
  getAllUsers,
  addUser,
  editUser,
  resetPassword,
  enableUser,
  disableUser,
  deleteUser
} from "@/api/user";
import { ElMessage, ElMessageBox, ElTable } from "element-plus";
import type { FormRules } from "element-plus";
defineOptions({
  name: "user"
});

type selection = {
  id?: string;
  userName?: string;
  password?: string;
  isAdmin?: string;
};
const shearchLoginname = ref("");
const shearchEnable = ref("");
const tableData = ref([]);
const loading = ref(false);
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref<selection[]>([]);
const dialogFormVisible = ref(false);
const passwordVisible = ref(false);
const passwordFormRef = ref(null);
const isEditMode = ref(false);
const rolesOptions = ref([
  { label: '普通用户', value: 0 },
  { label: '超级管理员', value: 1 }
]);
const statusOptions = ref([
  { label: '禁用', value: 0 },
  { label: '启用', value: 1 }
]);

/** 密码正则（密码格式应为8-18位数字、字母、符号的任意两种组合） */
const REGEXP_PWD =
  /^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)]|[()])+$)(?!^.*[\u4E00-\u9FA5].*$)([^(0-9a-zA-Z)]|[()]|[a-z]|[A-Z]|[0-9]){8,18}$/;
// 定义表单验证规则
const rules = {
  loginName: [{ required: true, message: '登录名不能为空', trigger: 'blur' }],
  userName: [{ required: true, message: '真实姓名不能为空', trigger: 'blur' }],
  password: [
    {
      validator: (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入密码"));
        } else if (!REGEXP_PWD.test(value)) {
          callback(
            new Error("密码格式应为8-18位数字、字母、符号的任意两种组合")
          );
        } else {
          callback();
        }
      },
      required: !isEditMode.value,
      trigger: 'blur'

    }
  ],
  isAdmin: [{ required: true, message: '角色不能为空', trigger: 'change' }],
};

const form = reactive({
  id: "",
  loginName: "",
  userName: "",
  password: "",
  department: "",
  enable: 1,
  isAdmin: ""
});
const passwordForm = reactive({
  id: "",
  newPassword: ""
});

const pagination = ref({
  total: 0,
  pageNum: 1,
  pageSize: 10,
})

const getUserList = async () => {
  try {
    loading.value = true;
    const res = await getAllUsers({
      loginName: shearchLoginname.value,
      enable: shearchEnable.value,
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize
    });
    loading.value = false;
    if (res.success) {
      tableData.value = res.data.list;
      pagination.value.total = res.data.total;
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    loading.value = false;
    ElMessage.error(error);
  }
};

const showDialog = () => {
  form.id = ""
  form.password = ""
  form.loginName = ""
  form.department = ""
  form.enable = 1
  form.userName = ""
  form.isAdmin = ""
  isEditMode.value = false; // 设置为新增模式
  dialogFormVisible.value = true;
}

const handleAddUser = async () => {
  try {
    loading.value = true;
    const res = form.id ? await editUser(form) : await addUser(form);
    loading.value = false;
    if (res.success) {
      getUserList();
      dialogFormVisible.value = false;
      ElMessage.success("操作成功");
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    loading.value = false;
    ElMessage.error(error);
  }
}

const handleEdit = async row => {
  console.log(row)
  form.loginName = row.loginName;
  form.id = row.id;
  form.userName = row.userName;
  form.isAdmin = row.isAdmin;
  form.password = row.password;
  form.department = row.department;
  form.enable = row.enable;
  isEditMode.value = true;
  dialogFormVisible.value = true;
};

const handleSelectionChange = (val: selection[]) => {
  multipleSelection.value = val;
};


const handleMultipleDel = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请选择要删除的数据");
    return;
  }

  // 确认删除提示框
  ElMessageBox.confirm('确定要删除选中的用户吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        loading.value = true;
        const res = await deleteUser({
          id: multipleSelection.value.map(item => item.id)
        });
        loading.value = false;
        if (res.success) {
          getUserList();
          ElMessage.success("删除成功");
        } else {
          ElMessage.error(res.msg);
        }
      } catch (error) {
        loading.value = false;
        ElMessage.error(error);
      }
    })
    .catch(() => {
      // 用户点击了取消，不执行任何操作
    });
};

const showPasswordDialog = async row => {
  console.log(row)
  passwordForm.id = row.id;
  passwordForm.newPassword = "";
  passwordVisible.value = true;
};

const handleResetPassword = async () => {
  // 进行表单验证
  await passwordFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请填写正确的表单信息');
      return;
    }
    try {
      loading.value = true;
      const res = await resetPassword({
        id: passwordForm.id,
        newPassword: passwordForm.newPassword
      });
      loading.value = false;
      if (res.success) {
        getUserList();
        ElMessage.success("修改成功");
        passwordVisible.value = false; // 关闭对话框
        return true;
      } else {
        ElMessage.error(res.msg);
        return false;
      }
    } catch (error) {
      loading.value = false;
      ElMessage.error(error);
      return false;
    }
  });
};

const passwordRules = reactive(<FormRules>{
  newPassword: [
    {
      validator: (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入密码"));
        } else if (!REGEXP_PWD.test(value)) {
          callback(
            new Error("密码格式应为8-18位数字、字母、符号的任意两种组合")
          );
        } else {
          callback();
        }
      },
      trigger: "blur",
      required: true,
    }
  ],
});

const handleSizeChange = (val: number) => {
  pagination.value.pageSize = val
  getUserList()
}
const handleCurrentChange = (val: number) => {
  pagination.value.pageNum = val
  getUserList()
}

onMounted(async () => {
  await getUserList();
});

const handleDisable = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请选择要禁用的用户");
    return;
  }
  try {
    loading.value = true;
    const res = await disableUser({
      id: multipleSelection.value.map(item => item.id)
    });
    loading.value = false;
    if (res.success) {
      getUserList();
      ElMessage.success("禁用成功");
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    loading.value = false;
    ElMessage.error(error);
  }
};

const handleEable = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请选择要激活的用户");
    return;
  }
  try {
    loading.value = true;
    const res = await enableUser({
      id: multipleSelection.value.map(item => item.id)
    });
    loading.value = false;
    if (res.success) {
      getUserList();
      ElMessage.success("激活成功");
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    loading.value = false;
    ElMessage.error(error);
  }
};
</script>


<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>用户管理</span>
      </div>
    </template>
    <div class="action-bar">
      <div class="flex justify-between w-full">
        <el-space>
          <el-form-item label="登录名：" style="margin-bottom: 0;">
            <el-input v-model="shearchLoginname" clearable placeholder="请输入登录名" style="width: 200px;" />
          </el-form-item>
          <el-form-item label="状态：" style="margin-bottom: 0;">
            <el-select v-model="shearchEnable" placeholder="--请选择--" clearable>
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-button type="primary" @click="getUserList">搜索</el-button>
        </el-space>
        <div>
          <el-button type="primary" @click="showDialog">新增用户</el-button>
          <el-button type="primary" @click="handleEable">激活用户</el-button>
          <el-button type="primary" @click="handleDisable">禁用用户</el-button>
          <el-button type="danger" @click="handleMultipleDel">删除用户</el-button>

        </div>
      </div>
    </div>
    <el-table ref="multipleTableRef" v-loading="loading" :data="tableData" stripe border style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="loginName" label="登录名" />
      <el-table-column prop="userName" label="真实姓名" />
      <el-table-column prop="department" label="部门/组" />
      <el-table-column prop="isAdmin" label="角色">
        <template #default="scope">
          <span>{{ scope.row.isAdmin ? '管理员' : '普通用户' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="enable" label="状态">
        <template #default="scope">
          <span>{{ scope.row.enable ? '启用' : '禁用' }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="160">
        <template #default="scope">
          <div class="item-action">
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button size="small" type="primary" @click="showPasswordDialog(scope.row)">
              重置密码
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="flex justify-end mt-[10px]">
      <el-pagination background layout="sizes, prev, pager, next, total" :total="pagination.total" :default-page-size="10"
        :current-page="pagination.pageNum" @update:current-page="handleCurrentChange" @size-change="handleSizeChange" />
    </div>
    <el-dialog v-model="dialogFormVisible" :title="isEditMode ? '编辑用户' : '新增用户'" width="500">
      <el-form :model="form" :rules="rules" label-width="80px" label-position="left">
        <el-form-item prop="loginName" label="登录名">
          <el-input v-model="form.loginName" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="userName" label="真实姓名">
          <el-input v-model="form.userName" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="department" label="部门/组">
          <el-input v-model="form.department" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="password" label="密码" v-if="!isEditMode">
          <el-input v-model="form.password" autocomplete="off" type="password" />
        </el-form-item>
        <el-form-item prop="isAdmin" label="角色">
          <el-select v-model="form.isAdmin" placeholder="--请选择--" clearable>
            <el-option v-for="item in rolesOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddUser">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="passwordVisible" title="重置密码" width="500">
      <el-form ref="passwordFormRef" :model="passwordForm" label-width="80px" label-position="left"
        :rules="passwordRules">
        <el-form-item prop="newPassword" label="新密码">
          <el-input v-model="passwordForm.newPassword" autocomplete="off" type="password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="passwordVisible = false">取消</el-button>
          <el-button type="primary" @click="handleResetPassword">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

  </el-card>
</template>

<style lang="scss" scoped>
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-action {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
</style>
